//////////////dohttp.cpp////////////////////

#include "dohttp.h"

DoHttp::DoHttp(QObject *parent) :
    QThread(parent),
    is_init(true)
{
}

void DoHttp::run()
{
    qDebug()<<"run"<<endl;
    if (is_init)
    {
        qnam = new QNetworkAccessManager();
        is_init = false;
    }

    startQuery(req);

}

void DoHttp::setReq(QString req)
{
    this->req = req;
    qDebug()<<req<<endl;
}

void DoHttp::startQuery(QString redirect_url)
{
    QString url;
    QString pattern = "^http://";

    QRegExp regExp("^http://");

    if(redirect_url.contains(regExp))
    {
         url = redirect_url;
         qDebug()<<url<<endl;
    }
    else
    {
        url = "http://" + redirect_url;
    }
    qDebug()<<redirect_url<<endl;
    QNetworkRequest request;


    // 设定url
    request.setUrl(QUrl(url));
    // 设定请求头
    request.setRawHeader("Host", req.toUtf8());
    request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setRawHeader("Accept-Language", "zh-cn,zh;q=0.5");
    // TODO:使用gzip
    request.setRawHeader("Accept-Encoding", "deflate");
    request.setRawHeader("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
    request.setRawHeader("Connection", "keep-alive");

    // 使用get方式发起请求
    reply = qnam->get(request);

/***************如果需要同步********************/
    qRegisterMetaType<QNetworkReply::NetworkError> ("QNetworkReply::NetworkError");
    QEventLoop loop; // 使用事件循环使得网络通讯同步进行
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
            SLOT(slot_httpError(QNetworkReply::NetworkError)));
    loop.exec(); // 进入事件循环， 直到reply的finished()信号发出， 这个语句才能
                        //退出
    slot_httpFinished();
/**************************************/

}

void DoHttp::slot_httpFinished()
{
    int http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (http_status == 302)
    {
        qDebug()<<"重定向"<<http_status<<endl;
        startQuery(reply->rawHeader("Location"));
    }else
    {
        QString data = QString::fromUtf8(reply->readAll());
        send_msg(data);

        if (reply->error() == QNetworkReply::NoError)
        {
//            saveToFile(reply_content);
        }else
        {
            qDebug() << "ERROR:" << query_word << " CODE:" << reply->error();
        }

    }

    reply->close();
    reply->deleteLater();


}

void DoHttp::slot_httpError(QNetworkReply::NetworkError)
{

}

